package com.campus.service.impl;

import com.campus.domain.dto.ActivityQueryDTO;
import com.campus.domain.dto.EnrollActivityDTO;
import com.campus.domain.dto.PublishActivityDTO;
import com.campus.domain.entity.Activity;
import com.campus.domain.entity.ActivityEnrollment;
import com.campus.domain.entity.ActivityImage;
import com.campus.domain.entity.User;
import com.campus.domain.vo.ActivityVO;
import com.campus.domain.vo.PageResultVO;
import com.campus.mapper.ActivityEnrollmentMapper;
import com.campus.mapper.ActivityImageMapper;
import com.campus.mapper.ActivityMapper;
import com.campus.mapper.UserMapper;
import com.campus.service.IActivityService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ActivityServiceImpl implements IActivityService {

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ActivityImageMapper activityImageMapper;

    @Autowired
    private ActivityEnrollmentMapper enrollmentMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public void publishActivity(PublishActivityDTO dto, Long userId) {
        // 获取用户信息
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 创建活动对象
        Activity activity = new Activity();
        activity.setTitle(dto.getTitle());
        activity.setDescription(dto.getDescription());
        
        // 时间格式转换
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startTime = LocalDateTime.parse(dto.getStartTime(), formatter);
        LocalDateTime endTime = LocalDateTime.parse(dto.getEndTime(), formatter);
        activity.setStartTime(startTime);
        activity.setEndTime(endTime);
        
        activity.setLocation(dto.getLocation());
        activity.setMaxParticipants(dto.getMaxParticipants() != null ? dto.getMaxParticipants() : 0);
        activity.setCurrentParticipants(0);
        activity.setPublisherId(userId);
        activity.setPublisherName(user.getUserName());
        
        // 根据当前时间和活动时间设置初始状态
        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(startTime)) {
            activity.setStatus(0); // 未开始
        } else if (now.isAfter(endTime)) {
            activity.setStatus(2); // 已结束
        } else {
            activity.setStatus(1); // 进行中
        }

        // 保存活动
        activityMapper.insert(activity);

        // 保存活动图片
        List<String> images = dto.getImages();
        if (images != null && !images.isEmpty()) {
            for (int i = 0; i < images.size(); i++) {
                ActivityImage image = new ActivityImage();
                image.setActivityId(activity.getId());
                image.setImageUrl(images.get(i));
                image.setSortOrder(i);
                activityImageMapper.insert(image);
            }
        }
    }

    @Override
    public PageResultVO<ActivityVO> getActivityList(ActivityQueryDTO queryDTO) {
        // 计算偏移量
        int offset = (queryDTO.getPage() - 1) * queryDTO.getSize();
        
        // 查询活动列表
        List<Activity> activities = activityMapper.selectList(
            queryDTO.getKeyword(), 
            queryDTO.getStatus(), 
            offset, 
            queryDTO.getSize()
        );
        
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        
        // 转换为VO并设置图片
        List<ActivityVO> voList = activities.stream().map(activity -> {
            ActivityVO vo = new ActivityVO();
            BeanUtils.copyProperties(activity, vo);
            
            // 根据时间动态计算活动状态
            if (now.isBefore(activity.getStartTime())) {
                vo.setStatus(0); // 未开始
            } else if (now.isAfter(activity.getEndTime())) {
                vo.setStatus(2); // 已结束
            } else {
                vo.setStatus(1); // 进行中
            }
            
            // 查询图片
            List<ActivityImage> images = activityImageMapper.selectByActivityId(activity.getId());
            vo.setImages(images.stream()
                .map(ActivityImage::getImageUrl)
                .collect(Collectors.toList()));
            
            return vo;
        }).collect(Collectors.toList());
        
        // 查询总数
        Long total = activityMapper.countTotal(queryDTO.getKeyword(), queryDTO.getStatus());
        
        return new PageResultVO<>(voList,total,queryDTO.getPage(),queryDTO.getSize());
    }

    @Override
    public ActivityVO getActivityDetail(Long activityId) {
        // 查询活动
        Activity activity = activityMapper.selectById(activityId);
        if (activity == null) {
            throw new RuntimeException("活动不存在");
        }
        
        // 转换为VO
        ActivityVO vo = new ActivityVO();
        BeanUtils.copyProperties(activity, vo);
        
        // 获取当前时间，动态计算活动状态
        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(activity.getStartTime())) {
            vo.setStatus(0); // 未开始
        } else if (now.isAfter(activity.getEndTime())) {
            vo.setStatus(2); // 已结束
        } else {
            vo.setStatus(1); // 进行中
        }
        
        // 查询图片
        List<ActivityImage> images = activityImageMapper.selectByActivityId(activityId);
        vo.setImages(images.stream()
            .map(ActivityImage::getImageUrl)
            .collect(Collectors.toList()));
        
        return vo;
    }

    @Override
    @Transactional
    public void enrollActivity(EnrollActivityDTO dto, Long userId) {
        // 检查活动是否存在
        Activity activity = activityMapper.selectById(dto.getActivityId());
        if (activity == null) {
            throw new RuntimeException("活动不存在");
        }
        
        // 检查活动状态
        if (activity.getStatus() == 2) {
            throw new RuntimeException("活动已结束，无法报名");
        }
        
        // 检查是否已报名（包括已取消的记录）
        ActivityEnrollment existingAny = enrollmentMapper.selectByActivityAndUserAnyStatus(dto.getActivityId(), userId);
        
        if (existingAny != null) {
            if (existingAny.getStatus() == 0) {
                // 已经是报名状态
                throw new RuntimeException("您已报名该活动");
            } else if (existingAny.getStatus() == 1) {
                // 之前取消过，现在重新报名，更新状态即可
                // 检查人数限制
                if (activity.getMaxParticipants() > 0) {
                    int currentCount = enrollmentMapper.countByActivityId(dto.getActivityId());
                    if (currentCount >= activity.getMaxParticipants()) {
                        throw new RuntimeException("名额已满，无法报名");
                    }
                }
                
                // 更新状态为已报名
                enrollmentMapper.updateStatus(dto.getActivityId(), userId, 0);
                
                // 更新活动报名人数
                int count = enrollmentMapper.countByActivityId(dto.getActivityId());
                activityMapper.updateCurrentParticipants(dto.getActivityId(), count);
                return;
            }
        }
        
        // 检查人数限制
        if (activity.getMaxParticipants() > 0) {
            int currentCount = enrollmentMapper.countByActivityId(dto.getActivityId());
            if (currentCount >= activity.getMaxParticipants()) {
                throw new RuntimeException("名额已满，无法报名");
            }
        }
        
        // 获取用户信息
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 创建报名记录
        ActivityEnrollment enrollment = new ActivityEnrollment();
        enrollment.setActivityId(dto.getActivityId());
        enrollment.setUserId(userId);
        enrollment.setUsername(user.getUserName());
        enrollment.setContactInfo(dto.getContactInfo());
        enrollment.setStatus(0); // 0-已报名
        
        enrollmentMapper.insert(enrollment);
        
        // 更新活动报名人数
        int count = enrollmentMapper.countByActivityId(dto.getActivityId());
        activityMapper.updateCurrentParticipants(dto.getActivityId(), count);
    }

    @Override
    @Transactional
    public void cancelEnroll(Long activityId, Long userId) {
        // 检查是否已报名
        ActivityEnrollment enrollment = enrollmentMapper.selectByActivityAndUser(activityId, userId);
        if (enrollment == null) {
            throw new RuntimeException("您未报名该活动");
        }
        
        // 取消报名（更新状态为1）
        enrollmentMapper.updateStatus(activityId, userId, 1);
        
        // 更新活动报名人数
        int count = enrollmentMapper.countByActivityId(activityId);
        activityMapper.updateCurrentParticipants(activityId, count);
    }

    @Override
    public boolean checkEnrollStatus(Long activityId, Long userId) {
        ActivityEnrollment enrollment = enrollmentMapper.selectByActivityAndUser(activityId, userId);
        return enrollment != null;
    }

    @Override
    @Transactional
    public void deleteActivity(Long activityId, Long userId) {
        // 检查活动是否存在
        Activity activity = activityMapper.selectById(activityId);
        if (activity == null) {
            throw new RuntimeException("活动不存在");
        }
        
        // 检查是否是活动发布者（只有发布者可以删除）
        if (!activity.getPublisherId().equals(userId)) {
            throw new RuntimeException("无权删除该活动");
        }
        
        // 检查活动是否有报名记录
        int enrollCount = enrollmentMapper.countByActivityId(activityId);
        if (enrollCount > 0) {
            throw new RuntimeException("该活动已有用户报名，无法删除");
        }
        
        // 删除活动图片
        activityImageMapper.deleteByActivityId(activityId);
        
        // 删除活动
        activityMapper.deleteById(activityId);
    }

    @Override
    @Transactional
    public void updateActivity(Long activityId, PublishActivityDTO dto, Long userId) {
        // 检查活动是否存在
        Activity activity = activityMapper.selectById(activityId);
        if (activity == null) {
            throw new RuntimeException("活动不存在");
        }
        
        // 更新活动基本信息
        activity.setTitle(dto.getTitle());
        activity.setDescription(dto.getDescription());
        
        // 时间格式转换
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startTime = LocalDateTime.parse(dto.getStartTime(), formatter);
        LocalDateTime endTime = LocalDateTime.parse(dto.getEndTime(), formatter);
        activity.setStartTime(startTime);
        activity.setEndTime(endTime);
        
        activity.setLocation(dto.getLocation());
        activity.setMaxParticipants(dto.getMaxParticipants() != null ? dto.getMaxParticipants() : 0);
        
        // 根据当前时间和活动时间更新状态
        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(startTime)) {
            activity.setStatus(0); // 未开始
        } else if (now.isAfter(endTime)) {
            activity.setStatus(2); // 已结束
        } else {
            activity.setStatus(1); // 进行中
        }
        
        // 更新活动
        activityMapper.updateActivity(activity);
        
        // 删除旧图片
        activityImageMapper.deleteByActivityId(activityId);
        
        // 保存新图片
        List<String> images = dto.getImages();
        if (images != null && !images.isEmpty()) {
            for (int i = 0; i < images.size(); i++) {
                ActivityImage image = new ActivityImage();
                image.setActivityId(activityId);
                image.setImageUrl(images.get(i));
                image.setSortOrder(i);
                activityImageMapper.insert(image);
            }
        }
    }
}

